//
//  BookMakerView.m
//  BookMaker
//
//  Created by Mathieu Tozer on 22/11/07.
//  Copyright 2007 plasq. All rights reserved.
//

#import "BookMakerView.h"
#import "Page.h"
#import "Image.h"
#import "PQMousing.h"
#import "BookMakerImageView.h"
@implementation BookMakerView

- (NSRect)imageViewRectFromPageRect:(NSRect)pageRect inView:(IKImageView *)view
{
	return [view convertImageRectToViewRect:pageRect];
}

- (NSRect)pageRectFromImageViewRect:(NSRect)pageRect inView:(IKImageView *)view
{
	return [view convertViewRectToImageRect:pageRect];
}

- (id)initWithPage:(Page *)page andView:(IKImageView *)view
{
    self = [super initWithFrame:[self imageViewRectFromPageRect:[page pageRect] inView:view]];
    if (self) {
		[self setPage:page];
	}
    return self;
}

- (void)drawRect:(NSRect)rect {
    // Drawing code here.
	
	[[[NSColor blackColor] colorWithAlphaComponent:0.4] set];
	[NSBezierPath fillRect:rect];
	
	int order = [[[self page] valueForKey:@"order"] intValue];
	NSAttributedString *orderString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%d", order]];
	[orderString drawAtPoint:NSZeroPoint];
}

- (Page *)page {
    return [[_page retain] autorelease];
}

- (void)setPage:(Page *)value {
    if (_page != value) {
        [_page release];
		[value retain];
        _page = value;
    }
}

- (void)startDraggingPageAround:(NSEvent *)event
{
//    NSPoint originalMouseLocation = [self convertPoint:[event locationInWindow] fromView:nil];
    while ([event type]!=NSLeftMouseUp) {
		event = [[self window] nextEventMatchingMask:(NSLeftMouseDraggedMask | NSLeftMouseUpMask)];		
		// Figure out a new x and y based on the new location
		float dX = [event deltaX];
		float dY = [event deltaY];	
		NSRect currentFrame = [self frame];
		currentFrame.origin = NSMakePoint(currentFrame.origin.x+=dX, currentFrame.origin.y-=dY);
		[[self page] setPageRect:[self pageRectFromImageViewRect:currentFrame inView:(IKImageView *)[self superview]]];
		[self setFrame:currentFrame];
    }
}

- (void)mouseDraggingStarted:(NSEvent *)event
{
	//start moving the view around the screen, updating the rect into the model
	[self startDraggingPageAround:event];
}

- (void)mouseDown:(NSEvent *)event
{
	[self dispatchCorrectMousingActionForEvent:event toObject:self];
}

- (BOOL)acceptsFirstResponder
{
	return YES;
}

@end
